<template>
  <div class="login-page">
    <div class="brand">
      <h1>🎫 娱乐票务管理系统</h1>
      <p>Admin Console</p>
    </div>
    <el-card class="login-card" shadow="always">
      <h2 class="title">管理员登录</h2>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="84px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入管理员用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item>
          <el-button class="login-btn" type="primary" :loading="loading" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { authAPI } from '@/api'

const router = useRouter()
const loading = ref(false)
const formRef = ref(null)
const form = ref({ username: '', password: '' })
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

async function handleLogin() {
  try {
    await formRef.value.validate()
    loading.value = true
    const resp = await authAPI.login({ usernameOrEmail: form.value.username, password: form.value.password })
    // 兼容返回结构：{ token, tokenType, expiresIn } 或 data 包裹
    const token = resp?.token || resp?.data?.token
    if (!token) {
      throw new Error('登录失败：未返回令牌')
    }
    localStorage.setItem('admin_token', token)
    ElMessage.success('登录成功')
    // 可选：获取管理员信息并保存
    try {
      const info = await authAPI.getAdminInfo()
      if (info) localStorage.setItem('admin_info', JSON.stringify(info))
    } catch (_) {}
    router.push('/')
  } catch (err) {
    ElMessage.error(err?.message || '登录失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-page {
  position: fixed;
  inset: 0;
  display: grid;
  place-items: center;
  padding: 24px;
  /* 渐变背景 + SVG纹理 + 遮罩层 */
  background:
    url('/src/assets/bg-pattern.svg') repeat,
    radial-gradient(1200px 600px at 20% 20%, #e3f2fd 0%, #90caf9 45%, #2196f3 100%);
}
.brand {
  position: absolute;
  top: 40px;
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
  color: #fff;
}
.brand h1 { margin: 0; font-size: 22px; }
.brand p { margin: 6px 0 0; opacity: .85; }

.login-card {
  width: 420px;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0,0,0,.18);
  backdrop-filter: saturate(130%) blur(6px);
}
.title { margin-bottom: 16px; }
.login-btn { width: 100%; }

@media (max-width: 480px) {
  .login-card { width: 92vw; }
}
</style>